/// <summary>
/// 格式化文件大小的JS方法
/// </summary>
/// <param name="filesize">文件的大小,传入的是一个bytes为单位的参数</param>
/// <returns>格式化后的值</returns>
function formatFileSize(fileSize) {
	if (fileSize < 1024) {
		return fileSize + 'B';
	} else if (fileSize < (1024 * 1024)) {
		var temp = fileSize / 1024;
		temp = temp.toFixed(2);
		return temp + 'KB';
	} else if (fileSize < (1024 * 1024 * 1024)) {
		var temp = fileSize / (1024 * 1024);
		temp = temp.toFixed(2);
		return temp + 'MB';
	} else {
		var temp = fileSize / (1024 * 1024 * 1024);
		temp = temp.toFixed(2);
		return temp + 'GB';
	}
}

function getHeight(name) {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: function(res) { // res - 各种参数
				let uobj = uni.createSelectorQuery().select(name)
				uobj.boundingClientRect(function(data) { // data - 各种参数
					resolve(data.height)
				}).exec()
			}
		})
	})
}

//时间转化
function timestampFormat(timestamp) {
	timestamp = timestamp / 1000

	function zeroize(num) {
		return (String(num).length == 1 ? '0' : '') + num;
	}

	var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
	var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

	var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
	var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象

	var Y = tmDate.getFullYear(),
		m = tmDate.getMonth() + 1,
		d = tmDate.getDate();
	var H = tmDate.getHours(),
		i = tmDate.getMinutes(),
		s = tmDate.getSeconds();
	if (timestampDiff < 60) { // 一分钟之内
		return "刚刚";
	} else if (timestampDiff < 3600) { // 一小时前以内
		return Math.floor(timestampDiff / 60) + "分钟前";
	} else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
		return '今天' + zeroize(H) + ':' + zeroize(i);
	} else {
		var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
		if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
			return '昨天' + zeroize(H) + ':' + zeroize(i);
		} else if (curDate.getFullYear() == Y) {
			return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
		} else {
			return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
		}
	}
}
//删除文件
function deleteFile(name) {
	return new Promise((resolve, reject) => {
		uni.removeSavedFile({
			filePath: '_downloads/user222/video/' + name,
			complete: function(res) {
				resolve(res)
			}
		});
	})
}
// 获取文件数据
function getFile(name) {
	return new Promise((resolve, reject) => {
		uni.getSavedFileInfo({
			filePath: '_downloads/user222/video/' + name,
			success: (res) => {
				resolve(res)
			}
		});
	})
}
//获取文件夹下所有文件
function getAllLoggerFile() {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(
			'_downloads/user222/video/', //指定的目录
			function(entry) {
				var directoryReader = entry.createReader(); //获取读取目录对象

				directoryReader.readEntries(
					function(entries) { //历遍子目录即可
						let flieList = []
						for (var i = 0; i < entries.length; i++) {
							let flie = {}
							flie.name = entries[i].name
							flieList.push(flie)
						}
						resolve(flieList)
					},
					function(err) {
						console.log("访问目录失败");
						reject(err)
					});
			},
			function(err) {
				console.log("访问指定目录失败:" + err.message);
				reject(err.message)
			});
	})
}


//我这个封装通过promise返回出去！！！
//我这个封装通过promise返回出去！！！
//创建数据库或者有该数据库就打开,    这一步必须要！
function openSqlite() {
	//创建数据库或者打开
	//这plus.sqlite只在手机上运行

	return new Promise((resolve, reject) => {
		plus.sqlite.openDatabase({
			name: 'downList', //数据库名称
			path: '_doc/downList.db', //数据库地址，uniapp推荐以下划线为开头，这到底存在哪里去了，我也不清楚，哈哈
			success(e) {
				resolve(e); //成功回调
			},
			fail(e) {
				reject(e); //失败回调
			}
		})
	})
}

//在该数据库里创建表格，   这一步也必须要！
//下面注释里说的都是说sql:'create table if not exists....这里
//userInfo是表格名，你也可以写其他的名，不能用数字作为表格名的开头！！！
//括号里是表格的结构，列，这里我写了四列，list,id,gender,avatar这四列
//list后面大写的英文是自动增加的意思，因为表格里的每一行必须有唯一标识
//这sql语句会数据库的应该都看的懂，我是前端菜鸡，所以详细说明以便跟我一样不懂sql的前端看
//"id" TEXT  意思是这一列放的值为字符串之类的，如果是想存数字之类的就改为INTEGER
//数据库不能存对象，数组
function userInfoSQL() {
	return new Promise((resolve, reject) => {
		//创建表格在executeSql方法里写
		plus.sqlite.executeSql({
			name: 'downList',
			//表格创建或者打开，后面为表格结构
			//sql:'create table if not exists downList("list" INTEGER PRIMARY KEY AUTOINCREMENT,"id" TEXT,"name" TEXT UNIQUE,"gender" TEXT,"avatar" TEXT,UNIQUE INDEX "index_Name"("name"))', 
			sql: 'create table if not exists downList("list" INTEGER PRIMARY KEY AUTOINCREMENT,"id" TEXT,"name" TEXT,"gender" TEXT,"avatar" TEXT)',
			success(e) {
				resolve(e);
			},
			fail(e) {
				reject(e);
			}
		})
	})
}

//向表格里添加数据
//根据表格的列来添加信息
//因为list列我设为自动增加，所以不用添加数据
//values里是传过来要存的值，我这里是动态的，单引号加双引号拼接
function addUserInformation(obj) {
	//判断有没有传参
	if (obj !== undefined) {
		//判断传的参是否有值
		var b = (JSON.stringify(obj) == "{}");
		if (!b) {
			//obj传来的参数对象
			var id = obj.id || null; //id
			var name = obj.name || null; //名称
			var gender = obj.gender || null; //性别
			var avatar = obj.avatar || null; //头像
			return new Promise((resolve, reject) => {
				plus.sqlite.executeSql({
					name: 'downList',
					//sql:'insert or ingore into downList(id,name,gender,avatar) values("'+id+'","'+name+'","'+gender+'","'+avatar+'")',
					sql: 'insert into downList(id,name,gender,avatar) values("' + id + '","' + name +
						'","' + gender + '","' + avatar + '")',
					success(e) {
						resolve(e);
					},
					fail(e) {
						reject(e);
					}
				})
			})
		} else {
			return new Promise((resolve, reject) => {
				reject("错误添加")
			})
		}
	} else {
		return new Promise((resolve, reject) => {
			reject("错误添加")
		})
	}
}

//查询获取数据库里的数据
//根据传过来的值来获取信息，我这里写了可以有两个条件来获取，都是动态的
//第一个参数为表格名，aa,bb分别为列名和列的值 ， cc,dd同前面
//传的参数按1,3,5来传，传一个，传三个，传五个参数，不能只传两个或者四个
function selectInformationType(name, aa, bb, cc, dd) {
	if (name !== undefined) {
		//第一个是表单名称，后两个参数是列表名，用来检索
		if (aa !== undefined && cc !== undefined) {
			//两个检索条件
			var sql = 'select * from ' + name + ' where ' + aa + '=' + bb + ' and ' + cc + '=' + dd + '';
		}
		if (aa !== undefined && cc == undefined) {
			//一个检索条件
			var sql = 'select * from ' + name + ' where ' + aa + '=' + bb + '';
		}
		if (aa == undefined) {
			var sql = 'select * from ' + name + '';
		}
		return new Promise((resolve, reject) => {
			plus.sqlite.selectSql({
				name: 'downList',
				sql: sql,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				}
			})
		})
	} else {
		return new Promise((resolve, reject) => {
			reject("错误查询")
		});
	}
}

//删除数据库里的数据
//参数跟上面查询获取数据一样
//传的参数按1,3,5来传，传一个，传三个，传五个参数，不能只传两个或者四个
function deleteInformationType(name, sol, qq, ww, ee) {
	if (name !== undefined && sol !== undefined) {
		//listId为表名,后面两个是列表名，检索用的
		if (ww !== undefined) {
			//两个检索条件
			var sql = 'delete from ' + name + ' where ' + sol + '="' + qq + '" and ' + ww + '=' + ee + '';
		} else {
			//一个检索条件
			var sql = 'delete from ' + name + ' where ' + sol + '="' + qq + '"';
		}
		return new Promise((resolve, reject) => {
			plus.sqlite.executeSql({
				name: 'downList',
				sql: sql,
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e);
				}
			})
		})
	} else {
		return new Promise((resolve, reject) => {
			reject("错误删除")
		});
	}
}

//修改数据表里的数据
//第一个参数为表格名，name为要修改的列名，cont为要修改为什么值，use,sel为搜索条件，分别是列名和列值
//传的参数按1,3,5来传，传一个，传三个，传五个参数，不能只传两个或者四个
function modifyInformation(listName, name, cont, use, sel) {
	//表格名，要修改地方的列名，修改后的内容，修改条件查询，列名，内容
	var sql;
	if (use == undefined) {
		sql = 'update ' + listName + ' set ' + name + '="' + cont + '"';
	} else {
		sql = 'update ' + listName + ' set ' + name + '="' + cont + '" where ' + use + '="' + sel + '"';
	}
	//where前面的是要修改的，后面的是条件，选择哪个
	return new Promise((resolve, reject) => {
		plus.sqlite.executeSql({
			name: 'downList',
			sql: sql,
			success(e) {
				resolve(e);
			},
			fail(e) {
				reject(e);
			}
		})
	})
}

//关闭数据库
function closeSQL(name) {
	return new Promise((resolve, reject) => {
		plus.sqlite.closeDatabase({
			name: 'downList',
			success(e) {
				resolve(e);
			},
			fail(e) {
				reject(e);
			}
		})
	})
}

//监听数据库是否开启
function isOpen(name, path) {
	var ss = name || 'downList';
	var qq = path || '_doc/downList.db';
	//数据库打开了就返回true,否则返回false
	var open = plus.sqlite.isOpenDatabase({
		name: ss,
		path: qq
	})
	return open;
}

//一次获取指定数据条数
//不想一次性把数据全拿过来就可以这样写
//id为表格名，desc代表倒序拿数据，正常是从第一条开始拿，倒序就从最后一条也是最新的一条数据开始拿
//limit 15 offset '+num+''，后面这是两个单引号，这句的意思是跳过多少条拿15条数据，num是动态值
//比如你刚开始给num设为0，那就从最后面的数据开始拿15条，你下次肯定不想再拿刚刚获取到的数据，所以可以让num为15，这样就能一步一步的拿完所有的数据
function pullSQL(id, num) {
	//id为表名，num为跳过多少条数据
	//根据list来倒序拿数据，跳过num条拿取15条
	return new Promise((resolve, reject) => {
		plus.sqlite.selectSql({
			name: 'downList',
			sql: 'select * from ' + id + ' order by list desc limit 15 offset ' + num + '',
			success(e) {
				resolve(e);
			},
			fail(e) {
				reject(e);
			}
		})
	})
}

//计算时间差
function timediff(begin_time, end_time) {
  //年月日时分秒转换为时间戳
  let beginTime = new Date(begin_time).getTime() / 1000;
  let endTime = new Date(end_time).getTime() / 1000;
  var starttime = "";
  var endtime = "";
  if (beginTime < endTime) {
    starttime = beginTime;
    endtime = endTime;
  } else {
    starttime = endTime;
    endtime = beginTime;
  }
  //计算天数
  const timediff = endtime - starttime;
  const hours = timediff / 3600;
  const rehours = hours.toFixed(2);
  const day = Math.floor(timediff / (60 * 60 * 24))
  return { rehours, day };
}

//最大值
function sortMaxPileOn(max) {
  let arr = [];
  let index = 0;
  let num;
  max.forEach(item => {
    if (item.endPileOn.pileSymbol == "+") {
      num = (item.endPileOn.beforePileOn * 1000) + (item.endPileOn.afterPileNo * 1)
    } else {
      num = item.endPileOn.beforePileOn * 1000 - item.endPileOn.afterPileNo * 1
    }
    arr.push(num)
  });
  let maxNumber = arr[0];
  for (let i = 0; i < arr.length; i++) {
    //if判断语句，找出最大值
    if (maxNumber < arr[i]) {
      maxNumber = arr[i];
      index = i;
    }
  }
  return { maxNumber, index };
}

//最小值
function sortMinPileOn(min) {
  let arr = [];
  let index = 0;
  let num;
  min.forEach(item => {
    if (item.startPileOn.pileSymbol == "+") {
      num = (item.startPileOn.beforePileOn * 1000) + (item.startPileOn.afterPileNo * 1)
    } else {
      num = item.startPileOn.beforePileOn * 1000 - item.startPileOn.afterPileNo * 1
    }
    arr.push(num)
  });
  let minNumber = arr[0];
  for (let i = 0; i < arr.length; i++) {
    //if判断语句，找出最小值
    if (minNumber > arr[i]) {
      minNumber = arr[i];
      index = i;
    }
  }
  return { minNumber, index };
}

//转换为时间格式 
function formatDate(time) {
	var date = new Date(time);
	var YY = date.getFullYear() + '-';
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	// return YY + MM + DD + " " + hh + mm + ss;
	return YY + MM + DD;
}

//包含时分秒
function formatDateTime(time) {
	var date = new Date(time*1000);
	var YY = date.getFullYear() + '-';
	var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
	var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
	var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
	var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
	var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
	return YY + MM + DD + " " + hh + mm + ss;
	// return YY + MM + DD;
}
//打开第三方地图
 function toMapAPP(latitude, longitude, name) {
	let url = "";
	if (plus.os.name == "Android") { //判断是安卓端
		plus.nativeUI.actionSheet({ //选择菜单
			title: "选择地图应用",
			cancel: "取消",
			buttons: [{
				title: "腾讯地图"
			}, {
				title: "百度地图"
			}, {
				title: "高德地图"
			}]
		}, function(e) {
			switch (e.index) {
				//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
				case 1:
					//注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
					url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=26JBZ-D2MC3-5EK3X-35CJR-2ECTT-Z5BJD`;
					break;
				case 2:
					url =
						`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
					break;
				case 3:
					url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
					break;
				default:
					break;
			}
			if (url != "") {
				url = encodeURI(url);
				//plus.runtime.openURL(url,function(e){})调起手机APP应用
				plus.runtime.openURL(url, function(e) {
					plus.nativeUI.alert("本机未安装该地图APP");
				});
			}
		})
	} else {
		// iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
		// 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
		//（如urlschemewhitelist:["iosamap","baidumap"]）  
		plus.nativeUI.actionSheet({
			title: "选择地图应用",
			cancel: "取消",
			buttons: [{
				title: "腾讯地图"
			}, {
				title: "百度地图"
			}, {
				title: "高德地图"
			}]
		}, function(e) {
			switch (e.index) {
				case 1:
					url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=26JBZ-D2MC3-5EK3X-35CJR-2ECTT-Z5BJD`;
					break;
				case 2:
					url =
						`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
					break;
				case 3:
					url =
						`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
					break;
				default:
					break;
			}
			if (url != "") {
				url = encodeURI(url);
				plus.runtime.openURL(url, function(e) {
					plus.nativeUI.alert("本机未安装该地图APP");
				});
			}
		})
	}
}


  function caculateTimeago(dateTimeStamp) {
  const minute = 1000 * 60;      // 把分，时，天，周，半个月，一个月用毫秒表示
  const hour = minute * 60;
  const day = hour * 24;
  const week = day * 7;
  const now = new Date().getTime();   // 获取当前时间毫秒
  const diffValue = now - dateTimeStamp;// 时间差
  let result = '';

  if (diffValue < 0) {
    return;
  }
  const minC = diffValue / minute;  // 计算时间差的分，时，天，周，月
  const hourC = diffValue / hour;
  const dayC = diffValue / day;
  const weekC = diffValue / week;
  if (weekC >= 1 && weekC <= 4) {
    result = ` ${parseInt(`${weekC}`, 10)}周前`;
  } else if (dayC >= 1 && dayC <= 6) {
    result = ` ${parseInt(`${dayC}`, 10)}天前`;
  } else if (hourC >= 1 && hourC <= 23) {
    result = ` ${parseInt(`${hourC}`, 10)}小时前`;
  } else if (minC >= 1 && minC <= 59) {
    result = ` ${parseInt(`${minC}`, 10)}分钟前`;
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = '刚刚';
  } else {
    const datetime = new Date();
    datetime.setTime(dateTimeStamp);
    const Nyear = datetime.getFullYear();
    const Nmonth = datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1;
    const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate();
    result = `${Nyear}-${Nmonth}-${Ndate}`;
  }
  return result;
}

export default {
	formatFileSize,
	getAllLoggerFile,
	getFile,
	timediff,
	timestampFormat,
	deleteFile,
	openSqlite,
	userInfoSQL,
	addUserInformation,
	selectInformationType,
	deleteInformationType,
	pullSQL,
	isOpen,
	closeSQL,
	modifyInformation,
	getHeight,
	sortMaxPileOn,
	sortMinPileOn,
	formatDate,
	formatDateTime,
	toMapAPP,
	caculateTimeago
}
